<?php

namespace App\Repositories\Api;

use App\Http\Services\LoginService;
use App\Models\Member;
use App\Models\MemberAddress;
use App\Models\MemberLabel;
use App\Models\Supplier;
use App\Models\WeappScene;
use App\Repositories\PictureMappingRepository;
use Cache;
use Exception;

class MemberRepository
{
    public const SECRET_KEY = '@4!@#$%@';
    private $_unset_fields = "update_time,accept_enlist_message,education_pic,work_auth_pic,id_front_pic,idcard,xm,mobile,kid_xm,kid_idcard,education_number,last_login_ip,reg_time";

    /**
     * 用户登录
     * @param string $phone
     * @param string $password
     * @return bool
     * @throws Exception
     */
    public function adminLogin($unionid = "", $openid = "")
    {
        if (!$openid)
            throw new Exception("unionid 解析错误，请重新解析", 1);

        $member = Member::where("weapp_openid", $openid)->first();
        if (empty($member)) return null;

        $loginService = new LoginService();
        $token = $loginService->authcode($member['id'], 'ENCODE');
        $tags = $this->getTypes($member['id']);

        return [
            "id" => $member['id'],
            "username" => $member['username'],
            "avatar" => $member['avatar'],
            "cancel" => $member['cancel'],
            'tags' => $tags ?? [],
            'is_deliver' => intval($member['is_deliver']),
            "token" => $token,
        ];

    }

    public function getIdByToken($token = "")
    {
        if (!$token) return "";
        $login = new LoginService();
        $adminId = $login->authcode($token, 'DECODE');

        return $adminId;
    }

    /**
     * 更新信息
     */
    public function updateFields($adminId, $data = [])
    {
        if (!$adminId) {
            throw new Exception("会员不存在");
        }
        Cache::forget("cache_member_" . md5($adminId)); //移除数据缓存

        return Member::where("id", "=", $adminId)->update($data);
    }

    public function saveOrUpdate($data = [], $uid = 0)
    {
        if ($uid) {
            return Member::where("id", "=", $uid)->update($data);
        } else {
            return Member::create($data);
        }
    }

    public function getAdminInfo($id = null, $show_contact = true)
    {
        if (!intval($id)) return "";

        $cache_key = "cache_member_" . md5($id);

        $res = Cache::get($cache_key);
        if (env("OPEN_CACHE") && $res) return $res;

        $res = Member::where("id", "=", $id)->first();
        if (!$res) return "";

        $res['last_login_time'] = date("Y-m-d H:i:s", $res['last_login_time']);

        $pictures = (new PictureMappingRepository())->getMappingBySearch([
            'object_id' => $res['id'],
            'object_type' => "member"
        ]);

        if (strtotime($res['birthday']) <= 0) {
            $res['birthday'] = "";
        }

        $res['pictures'] = $pictures;
        $res['id_code'] = md6($res['id']);

        if ($res['status'] == 1) {
            Cache::set($cache_key, $res);
        }

        //查看来源
        if ($res['subscribe_scene']) {
            $res['subscribe_scene_title'] = WeappScene::query()->where(['code' => $res['subscribe_scene']])->value("title");
        }

        return $res;
    }

    public function getByUnionid($unionid = "")
    {
        if (empty($unionid)) return "";
        $member = Member::where("unionid", "=", $unionid)->first();
        if (empty($member)) return "";
        $member['pictures'] = (new PictureMappingRepository())->getMappingBySearch([
            'object_id' => $member['id'],
            'object_type' => "member"
        ]);

        return $member;
    }

    public function getOne($adminId = 0)
    {
        if (!intval($adminId)) return [];

        $cache_key = "cache_member_" . md5($adminId);
        $member = Cache::get($cache_key);

        if (env("OPEN_CACHE") && $member)
            return $member;

        $member = Member::where("id", "=", $adminId)->first(['id', 'weapp_openid', 'username', 'integral', 'avatar', 'shop_supplier_id', 'is_replace_order', 'is_deliver', 'type', 'status']);
        if (!$member) return "";

        if (!empty($member['shop_supplier_id'])) {
            $member['supplier'] = Supplier::query()->where(['id' => $member['shop_supplier_id']])->first(['id', 'title', 'contact_name', 'contact_phone', 'banner']);
        }

        $member['tags'] = $this->getTypes($member['id']);
        if (in_array(2, $member['tags'])) {
            $member['type'] = 2;
        } else {
            $member['type'] = 1;
        }

        //查看来源
        if ($member['subscribe_scene']) {
            $member['subscribe_scene_title'] = WeappScene::query()->where(['code' => $member['subscribe_scene']])->value("title");
        }

        return $member;
    }

    // 获取基本信息
    public function getSimpleMember($id = 0, $type = 1, $show_contact = false, $load_img = false)
    {
        $fields = [
            1 => ["id", "username", "avatar", "status", 'is_deliver', 'is_pick', 'is_replace_order'],//推广返现
            //互选池 详情页
            2 => ["id", 'is_deliver', 'is_replace_order', "avatar", "username", "gender", "status", 'unionid', 'openid'],
            //附近的人 详情页
            3 => ["id", 'is_deliver', 'is_replace_order', 'is_pick', "avatar", "username", "location", "gender", "status", 'unionid', 'openid'],
        ];

        $field = $fields[$type];
        $cache_key = "cache_member_" . md5($id . '-' . $type);

        $res = Cache::get($cache_key);
        if (env("OPEN_CACHE") && $res) return $res;

        $res = Member::where("id", "=", $id)->first(!empty($field) ? $field : "*");
        $res['tags'] = $this->getTypes($res['id']);
        if ($res['status'] == 1 && env("OPEN_CACHE")) {
            Cache::set($cache_key, $res);
        }

        return $res;
    }

    /*
    * 判断用户账户余额
    * 返回 true    需要充值
    * 返回 false 不需要充值
    */
    public function check_account_balance($uid = 0, $price = 0)
    {

        if (empty($uid)) return;

        $member = Member::where("id", "=", $uid)->first(['account', 'account_temp']);

        if ($member) {
            if ($price) {
                return math_add(str_replace(',', '', $member['account']), $member['account_temp']) >= $price ? false : true;
            } else {
                return math_add(str_replace(',', '', $member['account']), $member['account_temp']) >= 0 ? false : true;
            }
        }
    }

    /**
     * 我的统计
     * @Author   thomashtao               bosslen
     * @DateTime 2022-07-08T19:31:59+0800
     * @return   [type]                   [description]
     */
    public function getMyStat()
    {
    }

    /**
     * 地址详情
     * @param $fitler
     * @return mixed
     */
    public function getAddressInfo($fitler)
    {
        return MemberAddress::query()->where($fitler)->first();
    }

    /**
     * 获取指引数据
     */
    public function getGuideTip()
    {
        return [
            ['title' => "订", 'tip' => "温馨提示：请在订餐时间内订餐，超过订餐时间，停止订餐！", "options" => [
                ['title' => "早", 'time' => "16:00~20:00"],
                ['title' => "中", 'time' => "16:00~20:00"],
                ['title' => "晚", 'time' => "16:00~20:00"],
            ]],
            ['title' => "送", 'tip' => "温馨提示：暂不支持指定时间送餐，所有订单均在送餐时间内集中送达，还请谅解！", 'class' => "book-song", "options" => [
                ['title' => "早", 'time' => "16:00~20:00"],
                ['title' => "中", 'time' => "16:00~20:00"],
                ['title' => "晚", 'time' => "16:00~20:00"],
            ]],
        ];
    }

    public function deleteAddress(int $id = 0, int $uid = 0)
    {
        $address = MemberAddress::query()->where(['id' => $id])->first();

        if (!$address)
            return retFail("地址不存在");

        if ($address['uid'] != $uid)
            return retFail("无权限");

        MemberAddress::query()->where(['id' => $id])->delete();
        return retSuc("删除成功");
    }


    /**
     * 获取用户类型
     * @param null $uid
     */
    public function getTypes($uid = null)
    {
        if (!intval($uid))
            return null;

        return MemberLabel::query()->where(["uid" => $uid])->pluck("type")->toArray();
    }

}
